<?php

namespace App\Admin\Controllers;

//use App\Admin\Actions\Post\FreezeUser;
use App\Admin\Actions\Post\UpdateWages;
use App\Admin\Cache\RedisKey;
use App\Admin\Exports\UserProfileExport;
use App\Admin\Extensions\RoleOp;
use App\Admin\Extensions\UserOp;
use App\Constants\RecommendedGradeCode;
use App\Http\Controllers\Controller;
use App\Model\AppChannel;
use App\Model\Guild\GuildHost;
use App\Model\GuildManage;
use App\Model\HostBlacklist;
use App\Model\IpBlacklist;
use App\Model\Message;
use App\Model\User;
use App\Model\UserActLog;
use App\Model\UserDevice;
use App\Model\UserForbidden;
use App\Model\UserFreezeLog;
use App\Model\UserProfile;
use App\Model\UserScore;
use App\Model\UserScoreLog;
use App\Model\UserTypeRule;
use App\Util\ComUtil;
use App\Util\DateUtil;
use App\Util\ImUtil;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class UserController extends Controller
{
    use ModelForm;

    /**
     * 用户列表
     *
     * @return Content
     */
    public function index()
    {
        $this->adminId = Admin::user()->id;
        $this->super = $this->adminId == 1;
        return Admin::content(function (Content $content) {
            $content->header('用户列表');
            $content->body($this->userList());
        });
    }

    /**
     * 声优列表
     *
     * @return Content
     */
    public function host()
    {
        return Admin::content(function (Content $content) {
            $content->header('女用户列表');
            $guildHosts = GuildHost::getAllHosts();
            $blackHosts = HostBlacklist::getUids();
            $content->body($this->hostList($guildHosts, $blackHosts));
        });
    }

    /**
     * 用户编辑
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('用户编辑');
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加用户');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * 用户列表
     * @return Grid
     */
    protected function userList()
    {
        $grid = new Grid(new User());
        // return Admin::grid(User::class, function (Grid $grid) {
        $where = [];
        $androidMarkets = config('app_busi.androidMarket');
        $grid->model()->where($where)->with('userProfile')->with('userCoin')->orderBy('id', 'desc');
        $grid->id('用户内部ID')->sortable();
        $grid->im_account('额外信息')->display(function () {
            $str = "融云ID：{$this->im_account}<br/>" .
                "IP：{$this->client_ip}<br/>" .
                "设备：{$this->device}<br/>" .
                "设备ID：{$this->device_id}<br/>";
            return $str;
        });
        $grid->userProfile()->user_profile_id('用户ID')->sortable();
        $grid->userProfile()->locate_city('定位城市');
        $grid->phone('手机号')->sortable();
        $grid->userCoin()->total_coin('账户总余额')->display(function () {
            return !$this->userCoin || ($this->userCoin->recharge_coin + $this->userCoin->income_coin)<0 ? 0 : $this->userCoin->recharge_coin + $this->userCoin->income_coin;
        })->sortable();
        $grid->userProfile()->complete_reg('是否完成注册')->display(function () {
            return $this->userProfile ? '完成' : '未完成';
        });
        $grid->userProfile()->nick_name('用户昵称');
        $grid->userProfile()->avatar('头像')->display(function ($data) {
            if (!$data) return '';
            return ComUtil::buidlImgaeHtml($data);
        });
        $grid->userProfile()->role('用户角色')->display(function ($role) {
            return $role == UserProfile::ROLE_HOST ? '认证女用户' : '普通用户';
        });
        $grid->userProfile()->charm_value('魅力值');
        $grid->userProfile()->rich_value('财富值');
        $grid->userProfile()->invite_code('邀请人ID');
        $grid->userProfile()->gender('性别')->display(function ($gender) {
            $this->gender = $gender;
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->userProfile()->birthday('年龄')->display(function ($birthday) {
            return DateUtil::newDateDiff($birthday, date('Y-m-d'), 'Y');
        });
        $grid->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        // $grid->register_way('注册方式')->display(function () {
        //     return '自主注册';
        // });
        $grid->channel('注册渠道')->display(function ($data) {
            return User::CHANNEL_TYPE[$data] ?? $data;
        });
        $grid->cur_channel('最新登录渠道')->display(function ($data) {
            return User::CHANNEL_TYPE[$data] ?? $data ;
        });
        $grid->version('当前版本号');
        $grid->updated_at('最后活跃时间')->display(function ($time) {
            $data = UserActLog::getLastItem($this->id);
            return $data ? (string)$data->created_at : '-';
        });
//        $grid->userScore()->type_id('用户等级')->display(function ($data) {
//            if (empty($data)){
//                return '未评级';
//            }
//
//            switch ($this->userProfile->gender){
//                case 1:
//                    $res = UserScore::MALE_GRADE_ARRAY[$data];
//                    break;
//                case 0:
//                    $res = UserScore::FEMALE_GRADE_ARRAY[$data];
//                    break;
//            }
//
//            return $res ?? '未评级';
//        });

        $grid->userScore()->type_id('用户分级')->editable('select',function ($data) {
            if ($data->userProfile && $data->userProfile->gender == 0){
                return UserScore::FEMALE_GRADE_TEXT_ARRAY;
            }

            return UserScore::MALE_GRADE_TEXT_ARRAY;
        });

        $grid->userScore()->type('用户分级状态')->display(function ($data) {
            if (empty($data)){
                return '-';
            }
            return UserScore::OPERATE_ARRAY[$data];
        });

        $grid->userProfile()->is_recommend('展示状态')->display(function ($data) {
            return $data == 1 ? '推荐' : ($data == 0 ? '正常展示' : '不展示');
        });
        $grid->status('账号状态')->display(function ($data) {
            $str = User::STATUS[$data];
            return $str;
        });
        $grid->freezeStatus('冻结记录')->display(function () {
            $str = '';
            $reason = UserFreezeLog::checkReason($this->id);
            // $reason && $str .= "{$reason['text']}；";
            $reason && $str .= "冻结次数：{$reason['count']}";
            return $str;
        })->modal('冻结记录', function ($model) {
            $list = UserFreezeLog::where([
                'user_id' => $this->id,
            ])->take(30)->orderBy('id', 'desc')->get()->map(function ($item) {
                return $item->only(['act', 'reason_type', 'reason', 'created_at']);
            })->toArray();
            foreach ($list as &$item) {
                $item['act'] = $item['act'] == 1 ? '冻结' : '解封';
                $item['reason_type'] = UserFreezeLog::REASON_TYPE[$item['reason_type']];
            }
            return new Table(['操作', '理由', '理由说明', '操作时间'], $list);
        });
        //禁用导出
        if (!$this->super) {
            $grid->disableExport();
        } else {
            $grid->exporter(new UserProfileExport($grid));
        }
        //禁用新增
        $grid->disableCreation();
        //禁用行选择
        $grid->disableRowSelector();
        $grid->filter(function ($filter) use ($androidMarkets) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '用户ID');
                $filter->equal('im_account', 'IM账号');
                $filter->equal('status', '状态')->select(User::STATUS);
                $filter->between('userProfile.birthday', '出生日期')->datetime();
                $filter->equal('client_ip', 'IP地址');
                $filter->equal('device_id', '设备ID');
            });
            $filter->column(1 / 3, function ($filter) use ($androidMarkets) {
                $filter->equal('userProfile.user_id', '内部ID');
                $filter->like('phone', '手机号');
                $filter->equal('platform', '注册平台')->select(User::PLATFORM);
                $filter->equal('version', '用户版本号');
                $filter->equal('userProfile.role', '角色')->select([UserProfile::ROLE_HOST => '认证女用户', UserProfile::ROLE_USER => '用户']);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('userProfile.nick_name', '用户昵称');
                $filter->equal('userProfile.gender', '性别')->select([0 => '女', 1 => '男', -1 => '其他']);
                $filter->between('created_at', '注册时间')->datetime();
                $filter->equal('channel', '注册渠道')->select(AppChannel::pluck('channel_name', 'channel')->toArray());
                $filter->equal('userProfile.locate_city', '定位城市');
                $filter->equal('userScore.type_id','用户评级')->select(UserScore::GRADE_TEXT_ARRAY);
            });
        });

        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();
            // $actions->add(new FreezeUser());
            $actions->append(new UserOp(
                $actions->getKey(),
                $actions->row,
                'user/verify'
            ));
        });
        return $grid;
        // });
    }

    function verify()
    {
        $userId = request('id');
        $status = request('status');
        $action = request('action');
        $extra = request('extra');
        $record = User::find($userId);
        if (!$record) return ['ret' => -1, 'message' => '记录不存在'];
        $oldStatus = $record->status;
        switch ($action) {
            case 'status':
                //修改状态
                $record->update(['status' => $status]);
                break;
            case 'rec':
                //修改推荐状态
                UserProfile::where('user_id', $userId)->limit(1)->update(['is_recommend' => $status]);
                break;
            //女用户操作
            case 'role':
                UserProfile::where('user_id', $userId)->limit(1)->update(['role' => $status]);
                break;
            //冻结该IP
            case 'freeze_ip':
                $clientIp = request('extra');
                $userIds = User::where('client_ip', $clientIp)->pluck('id')->toArray();
                $count  = count($userIds);
                if ($count > 50) return ['ret' => -1, 'message' => '用户数量超过50个，请一一操作'];
                User::whereIn('id', $userIds)->limit($count)->update(['status' => $status]);
                ImUtil::kickOut($userIds);
                UserDevice::freezeUserDevice($userIds);
                //加入IP黑名单
                IpBlacklist::addIp($clientIp);
                Log::info(__METHOD__ . "==Action:{$action}=={$clientIp}==" . json_encode($userIds));
                break;
            case 'freeze_ip_device':
                $clientIp = request('extra');
                $userIds = User::where('client_ip', $clientIp)->pluck('id')->toArray();
                $count  = count($userIds);
                if ($count > 50) return ['ret' => -1, 'message' => '用户数量超过50个，请一一操作'];
                User::whereIn('id', $userIds)->limit($count)->update(['status' => $status]);
                ImUtil::kickOut($userIds);
                UserDevice::freezeUserDevice($userIds);
                //加入IP黑名单
                IpBlacklist::addIp($clientIp);

                //修改状态
                $record->update(['status' => $status]);

                //理由
                UserFreezeLog::addRecord($userId, intval(request('reason_type')), 1, request('reason'));

                Log::info(__METHOD__ . "==Action:{$action}=={$clientIp}==" . json_encode($userIds));
                break;
//            case 'default_avatar':
//                UserProfile::setDefaultAvatar($record->user_id, $record);
//                break;
        }
        if ($action == 'status') {
            switch ($status) {
                //冻结
                case User::STATUS_FREEZE:
                    //融云踢下线
                    ImUtil::kickOut($userId);
                    //设备封禁
                    $extra == 'device' && UserDevice::freezeUserDevice($userId);
                    //理由
                    UserFreezeLog::addRecord($userId, intval(request('reason_type')), 1, request('reason'));
                    break;
                //取消冻结
                case User::STATUS_OK:
                    //融云取消踢下线
                    ImUtil::cancelKickOut($userId);
                    //设备解封
                    UserDevice::unFreezeUserDevice($userId);
                    //理由
                    UserFreezeLog::addRecord($userId, 0, 0, '');
                    //解除禁言
                    UserForbidden::cancelForbidden($userId);
                    if ($oldStatus == User::STATUS_FORBID) {
                        $msg = "你的账号已解封，私信等功能可正常使用，如再次出现违规情况，该账号将会被直接封号。请你在平台内文明交友，共建和谐交友环境！谢谢~";
                        Message::pushSystem($userId, $msg, '解封通知');
                    }
                    break;
                //注销
                case User::STATUS_CANCELLATTED:
                    User::cancelAccount($userId);
                    break;
                //禁言
                case User::STATUS_FORBID:
                    $minutes = intval(request('extra'));
                    UserForbidden::doForbidden($userId, $minutes, 0, intval(request('reason_type')), request('reason'));
                    if ($minutes >= 5256000) {
                        $msg = "经审核发现，你的账号在平台出现违规行为，现将此账号作出永久禁言处理，禁言期间暂时无法使用私信等功能。如有疑问，请联系在线客服";
                    } else {
                        $days = $minutes / 1440;
                        $msg = "经审核发现，你的账号在平台出现违规行为，现将此账号作出禁言 {$days} 天处理，禁言期间暂时无法使用私信等功能。如有疑问，请联系在线客服";
                    }

                    Message::pushSystem($userId, $msg, '封禁通知');
                    break;
            }
        } elseif ($action == 'real_avatar') {
            UserProfile::where('user_id', $userId)->limit(1)->update(['avatar_vrfy' => $status]);
        } elseif ($action == 'default_avatar'){
            UserProfile::setDefaultAvatar($record->id);

            // 头像违规，把真人认证修改未认证
            UserProfile::where('user_id', $userId)->limit(1)->update(['avatar_vrfy' => 0]);

            // 真人认证不通过后，女生角色修改
            $userProfile = UserProfile::getProfile($userId);
            if ($userProfile->gender == 0) {
                UserProfile::where('user_id', $userId)->limit(1)->update(['role' => UserProfile::ROLE_USER]);
            }
        }
        Log::info(__METHOD__ . "==Uid:{$userId}==Action:{$action}==Status:{$status}");
        return ['ret' => 0, 'message' => '操作成功！'];
    }

    /**
     * 用户编辑
     * @return Form
     */
    protected function form()
    {
        return Admin::form(User::class, function (Form $form) {
            $form->display('id', '用户内部ID');
            $form->display('userprofile.user_profile_id', '用户ID')->default('');
            $form->text('userprofile.nick_name', '昵称')->default('');
            $form->display('phone', '电话')->default('');
            $form->date('userprofile.birthday', '生日')->default('');
            // $form->text('userprofile.city', '城市')->default('保密');
            $form->display('version', '版本')->default('');
            $form->display('im_account', 'IM账号')->default('');
            $form->select('userprofile.gender', '性别')->options([0 => '女', 1 => '男']);
            $form->select('official', '是否官方')->options([0 => '正常用户', 1 => '官方']);
            $form->text('userprofile.charm_value', '魅力值');
            $form->text('userprofile.rich_value', '财富值');
            $form->hidden('user_score.type_id','修改评级')->default(null);
            $form->hidden('user_score.host_rel','修改评级')->default(null);
////            $form->display('user_score.type','修改评级规则')->default(null);
//
//            $form->saving(function (Form $form) {
//
//                // $form->userprofile()->city = $form->userprofile()->city?:'保密';
//
//            });

            $form->saving(function (Form $form) {

                $data = $form->model();
                $userId = $data->id;
                if (!empty($form->user_score['type_id'])){
                    $profile = UserProfile::getProfile($data->id);

                    if (empty($profile)){
                        return response()->json([
                            'status' => false,
                            'message' => '此人没有完善信息:用户id='.$data->id
                        ]);
                    }

                    if (!in_array($profile->gender,[0,1])){
                        return response()->json([
                            'status' => false,
                            'message' => '此人没有完善信息:用户id='.$data->id
                        ]);
                    }

                    $scoreInfo = UserScore::getInfoByUserId($userId);
                    $redis = Redis::connection('default');
                    $redis->setOption(\Redis::OPT_PREFIX, '');
                    if (!empty($form->user_score['type_id'])){
                        $code = UserScore::GRADE_ARRAY[$form->user_score['type_id']];

                        if (empty($code)){
                            return response()->json([
                                'status' => false,
                                'message' => '操作错误'
                            ]);
                        }


                        //更新等级记录
                        UserScore::updateOrCreate([
                            'user_id' => $data->id
                        ],[
                            'type' => 1,
                            'type_id' => $form->user_score['type_id'],
                        ]);

                        UserScoreLog::create([
                            'user_id' => $data->id,
                            'type_id' => $form->user_score['type_id'],
                            'type' => 1
                        ]);

                        $key = RedisKey::todayUserGradeList($code);
                        $redis->sAdd($key,$userId);
                    }else{
                        UserScore::where('user_id',$data->id)->delete();

                        UserScoreLog::create([
                            'user_id' => $data->id,
                            'type_id' => 0,
                            'type' => 3
                        ]);
                    }

                    if (!empty($scoreInfo))
                    {
                        $oldCode = UserScore::GRADE_ARRAY[$scoreInfo->type_id];

                        $oldKey = RedisKey::todayUserGradeList($oldCode);
                        $redis->sRem($oldKey,$userId);
                    }


                    return response()->json([
                        'status' => true,
                        'message' => '操作成功'
                    ]);
                }
                if(!$form->user_score['host_rel']){
                    //更新等级记录
                    UserScore::updateOrCreate([
                        'user_id' => $data->id
                    ],[
                        'host_rel' => $form->user_score['host_rel'],
                    ]);
                    return response()->json([
                        'status' => true,
                        'message' => '操作成功'
                    ]);
                }
            });
        });
    }

    public function updateScore($id){
//         = $id;
        $data = request()->all();
        $id = $data['pk'];

        $profile = UserProfile::where('id',$id)->first();

        if (empty($profile)){
            return response()->json([
                'status' => false,
                'message' => '此人没有完善信息'
            ]);
        }

        if (!in_array($profile->gender,[0,1])){
            return response()->json([
                'status' => false,
                'message' => '此人没有完善信息'
            ]);
        }

        $userId = $profile->user_id;

        $scoreInfo = UserScore::getInfoByUserId($userId);
        $redis = Redis::connection('default');
        $redis->setOption(\Redis::OPT_PREFIX, '');
        if (!empty($data['value'])){

            switch ($profile->gender){
                case 0:
                    $code = UserScore::FEMALE_GRADE_ARRAY[$data['value']];
                    break;
                case 1:
                    $code = UserScore::MALE_GRADE_ARRAY[$data['value']];
                    break;
            }

            if (empty($code)){
                return response()->json([
                    'status' => false,
                    'message' => '操作错误'
                ]);
            }

            //更新等级记录
            UserScore::updateOrCreate([
                'user_id' => $userId
            ],[
                'type' => 1,
                'type_id' => $data['value'],
            ]);


            UserScoreLog::create([
                'user_id' => $userId,
                'type_id' => $data['value'],
                'type' => 1
            ]);

            $key = RedisKey::todayUserGradeList($code);
            $redis->sAdd($key,$userId);
        }else{
            UserScore::where('user_id',$userId)->delete();

            UserScoreLog::create([
                'user_id' => $userId,
                'type_id' => 0,
                'type' => 3
            ]);
        }


        if (!empty($scoreInfo))
        {
            switch ($profile->gender){
                case 0:
                    $oldCode = UserScore::FEMALE_GRADE_ARRAY[$scoreInfo->type_id];
                    break;
                case 1:
                    $oldCode = UserScore::MALE_GRADE_ARRAY[$scoreInfo->type_id];
                    break;
            }

            $oldKey = RedisKey::todayUserGradeList($oldCode);
            $redis->sRem($oldKey,$userId);
        }

        return response()->json([
            'status' => true,
            'message' => '修改评级成功'
        ]);
    }

    /**
     * 声优列表
     * @return Grid
     */
    protected function hostList($guildHosts = [], $blackHosts = [])
    {
        $grid = new Grid(new UserProfile());
        $where = [
            ['role', UserProfile::ROLE_HOST]
        ];

        $adminId = Admin::user()->id;
        if($adminId == 48 ){
            return [];
        }
        if($adminId == 48 || in_array($adminId,[49,50,51])){
            $guidIds = GuildManage::getGuidIdByAdminId($adminId);
            $hostIds = GuildHost::getHostUidByAdminId($guidIds);

            $grid->model()->where($where)->whereIn('user_id',$hostIds)->orderBy('id', 'desc');
        }else{
            $grid->model()->where($where)->orderBy('id', 'desc');
        }


        $grid->batchActions(function ($batch) {
            $batch->disableDelete();
        });
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new UpdateWages());
        });
        $grid->user_id('内部ID')->sortable();
        $grid->user_profile_id('女用户ID')->sortable();
        $grid->online('当前在线')->display(function ($data) {
            return $data == 1 ? '在线' : '-';
        });
        $grid->avatar('头像')->display(function ($data) {
            if (!$data) return '';
            return ComUtil::buidlImgaeHtml($data);
        });
        $grid->avatar_vrfy('真人照片认证')->display(function ($data) {
            return $data && $this->avatar ? "认证" : "-";
        });
        $grid->avatar_vrfy('真人照片认证')->display(function ($data) {
            return $data && $this->avatar ? "认证" : "-";
        });
        $grid->charm_value('魅力值')->sortable();
        $grid->nick_name('昵称');
        // $grid->userItem()->channel('注册渠道号');
        $grid->gender('性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->birthday('年龄')->display(function ($birthday) {
            return DateUtil::newDateDiff($birthday, date('Y-m-d'), 'Y');
        });

        $grid->coin_setting('语音收费设置')->display(function ($coin) {
            return "{$coin} 金币/分钟";
        });
        $grid->video_coin_setting('视频收费设置')->display(function ($coin) {
            return "{$coin} 金币/分钟";
        });
        $grid->chat_coin_setting('私聊收费设置')->display(function ($coin) {
            return "{$coin} 金币/分钟";
        });
        $grid->city('所在城市');
//        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
//            return isset($guildHosts[$this->user_id]) ? $guildHosts[$this->user_id] : '';
//        });
        $grid->host_time('成为女用户时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', $time);
        });
        $grid->created_at('注册时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->updated_at('最后活跃时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });

        // $blackHosts = HostBlacklist::getUids();
        $grid->black('是否黑名单')->display(function ($data) use ($blackHosts) {
            return in_array($this->user_id, $blackHosts) ? '拉黑' : '-';
        });
        $grid->hostInfo()->video_answer_time('视频接听时长')->sortable();
        $grid->hostInfo()->video_answer_num('视频次数')->sortable();
        $grid->hostInfo()->voice_answer_time('语音接听时长')->sortable();
        $grid->hostInfo()->video_answer_num('语音次数')->sortable();

        $grid->userScore()->type_id('用户分级')->editable('select',UserScore::FEMALE_GRADE_TEXT_ARRAY);
//        $grid->userScore()->host_rel('用户验证状态')->editable('select',UserScore::HOST_REL);

        $grid->userScore()->type('用户分级状态')->display(function ($data) {
            if (empty($data)){
                return '-';
            }
            return UserScore::OPERATE_ARRAY[$data];
        });
        //禁用导出
        $grid->disableExport();
        //禁用行选择
        // $grid->disableRowSelector();
        //禁用新增
        $grid->disableCreation();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('user_profile_id', '用户ID');
                $filter->equal('nick_name', '用户昵称');
                $filter->between('birthday', '出生日期')->datetime();
                $filter->equal('is_recommend', '是否首页推荐')->select([1 => '推荐', 0 => '不推荐']);
                $filter->between('updated_at', '最新活跃时间')->datetime();
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->like('userItem.phone', '手机号');
                $filter->between('created_at', '注册时间')->datetime();
                $filter->equal('gender', '性别')->select([0 => '女', 1 => '男', -1 => '其他']);
                $filter->equal('online', '是否在线')->select([1 => '在线', 0 => '不在线']);
                $filter->equal('userScore.type_id','用户分级')->select(UserScore::FEMALE_GRADE_TEXT_ARRAY);
//                $filter->where(function ($query) {
//                    $userIds = GuildHost::where('guild_manage_id', $this->input)->pluck('host_user_id')->toArray();
//                    $query->whereIn('user_id', $userIds);
//                }, '所属代理')->select('/get_guilds');
            });
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) use ($blackHosts) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
            $actions->append(new RoleOp(
                $actions->getKey(),
                $actions->row,
                'host/cancel',
                ['black_hosts' => $blackHosts]
            ));
        });
        return $grid;
    }

    function host_cancel()
    {
        $id = request('id');
        $action = request('action');
        $record = UserProfile::find($id);
        if (!$record) return ['ret' => -1, 'message' => '记录不存在'];
        if ($action == 'blacklist') {
            HostBlacklist::addHost($record->user_id);
        } elseif ($action == 'remove_blacklist') {
            HostBlacklist::removeHost($record->user_id);
        } elseif ($action == 'default_avatar') {
            UserProfile::setDefaultAvatar($record->user_id, $record);
        } elseif ($action == 'rec') {
            $record->update(['is_recommend' => intval(request('status'))]);
        } else {
            \Log::info(__CLASS__ . "==hostCancel=={$record->user_id}");
            $record->update(['role' => UserProfile::ROLE_USER]);
        }
        return ['ret' => 0, 'message' => '操作成功！'];
    }

}
